<template>
  <div>
    <el-dialog
      :title="isEdit ? '修改' : title"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="封面">
          <el-upload
            class="upload-demo"
            accept=".jpeg,.png,.jpg,.bmp,.gif,.webp"
            :action="uploadUrl"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :headers="headers"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :on-success="handleSuccess"
            :on-error="handleError"
            list-type="picture-card"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="form.theme" clearable></el-input>
        </el-form-item>
        <el-form-item label="副标题">
          <el-input v-model="form.subTitle" clearable></el-input>
        </el-form-item>
        <el-form-item label="提供部门">
          <el-input v-model="form.department" clearable></el-input>
        </el-form-item>
        <el-form-item label="提供人">
          <el-input v-model="form.provider" clearable></el-input>
        </el-form-item>
        <el-form-item label="批准人">
          <el-input v-model="form.approver" clearable></el-input>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="form.publishDate"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否置顶">
          <el-checkbox
            v-model="form.isTop"
            :true-label="1"
            :false-label="0"
          ></el-checkbox>
        </el-form-item>
        <el-form-item label="内容">
          <div style="border: 1px solid #ccc" class="editor">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 400px; overflow-y: hidden"
              v-model="form.content"
              @input="handleInput"
              :defaultConfig="editorConfig"
              :defaultContent="defaultContent"
              :mode="mode"
              @onCreated="onCreated"
              @onChange="onChange"
              @onMaxLength="onMaxLength"
            />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import news from '@/api/news/index'
import { getToken } from '@/utils/auth'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { DomEditor } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
import { Loading } from 'element-ui'
export default {
  name: 'TrainingDialog',
  components: {
    Editor,
    Toolbar,
  },
  props: {
    title: {
      type: String,
      default: '新增',
    },
  },
  computed: {
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + '/public/file/upload'
    },
    headers() {
      return { Authorization: getToken() }
    },
  },
  data() {
    return {
      dialogVisible: false,
      isEdit: false, //是否编辑
      form: {
        id: '',
        theme: '',
        cover: '', //封面
        department: '', //部门
        provider: '', //提供人
        approver: '', //批准人
        subTitle: '', //副标题
        publishDate: '', //发布时间
        isTop: 0, //是否置顶
        content: '', //描述
      },
      fileList: [
        {
          name: '',
          url: '',
        },
      ],
      editor: null,
      mode: 'default', // or 'simple'
      toolbarConfig: {
        // 排除工具栏配置
        excludeKeys: [
          // 全屏，网络视频，本地视频，表情，代码，待办，代码块，插入图片
          'fullScreen',
          'uploadVideo',
          'group-video',
          'emotion',
          'code',
          'todo',
          'codeBlock',
          'insertImage',
        ],
        insertKeys: {
          keys: ['ParagraphSpacingBefore', 'ParagraphSpacingAfter'],
          index: 10,
        },
      },
      editorConfig: {
        placeholder: '请输入内容...',
        maxLength: this.maxLength, // 限制富文本输入文本字数
        MENU_CONF: {
          uploadImage: {
            // 最多可上传几个文件，默认为 100
            // maxNumberOfFiles: 10,
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024 * 50, // 1M
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 5 * 1024, // 5kb
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制
            allowedFileTypes: ['image/*'],
            // 图片上传
            async customUpload(file, insertFn) {
              const formData = new FormData()
              formData.append('file', file)
              let loading = Loading.service({
                fullscreen: true,
                lock: true,
                text: '正在加载，请耐心等待...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
              })
              news
                .upFile(formData)
                .then((res) => {
                  loading.close()
                  insertFn(res.url, 'image')
                })
                .catch(() => {
                  loading.close()
                })

              // const res = await uploadF(formData)
              // if (res.data) {
              //     insertFn(`图片地址`, 'image')
              // } else {
              //     this.$message.error('图片上传失败，请重新上传!');
              // }
            },
          },
          fontFamily: {
            fontFamilyList: [
              { name: '仿宋', value: 'fangsong' },
              { name: '黑体', value: 'Arial' },
              { name: '宋体', value: 'SimSun' },
              { name: '楷书', value: 'KaiTi' },
              { name: '隶书', value: 'LiSu' },
            ],
          },
          lineHeight: {
            lineHeightList: ['1', '1.5', '1.75', '2', '2.5'],
          },
        },
      },
      defaultContent: [
        {
          type: 'paragraph',
          lineHeight: '1.75',
          children: [
            {
              fontSize: '16px',
              lineHeight: '1.75',
              color: 'rgba(0, 0, 0, 0.85)',
              text: '',
            },
          ],
        },
      ],
    }
  },
  computed: {
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + '/public/file/upload'
    },
    headers() {
      return { Authorization: getToken() }
    },
  },

  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      this.$nextTick(() => {
        const toolbar = DomEditor.getToolbar(this.editor)
        this.curToolbarConfig = toolbar.getConfig()
      })
    },
    handleInput(value) {
      this.$emit('change', value) // 将内容同步到父组件中
    },
    onChange(editor) {
      // 监听富文本输入
      const text = editor.getText().replace(/\n|\r/gm, '')
      this.textLength = text.length
    },
    onMaxLength(editor) {
      // 当输入值达到限制值时触发事件
      this.$message.warning('输入文本数已到达最大值！')
    },
    submitHandle() {
      this.form.cover = this.fileList[0].url
      if (this.isEdit) {
        //修改
        news
          .editHandle(this.form)
          .then((res) => {
            this.dialogVisible = false
            this.$notify({ message: '操作成功', type: 'success' })
            this.$emit('submitSuccess')
          })
          .catch(() => {})
      } else {
        news
          .addHandle(this.form)
          .then((res) => {
            this.dialogVisible = false
            this.$notify({ message: '操作成功', type: 'success' })
            this.$emit('submitSuccess')
          })
          .catch(() => {})
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess(response, file, fileList) {
      console.log(file)
      this.fileList = [
        {
          name: file.name,
          url: file.response.data.url,
        },
      ]
    },
    handleError() {
      this.$notify({ message: '上传失败', type: 'error' })
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      // for (let index = 0; index < fileList.length; index++) {
      //     const element = fileList[index];
      //     if (element.id == file.id) {
      //         fileList.splice(index, 1);
      //         break;
      //     }
      // }
      // this.form.tbPlatformGoodsFileList = fileList;
    },
  },
}
</script>

<style lang="scss">
// .w-e-text-container [data-slate-editor] p {
//   margin: auto;
// }
</style>
